/**
 * 
 */
package name.webdizz.gadget.four.envelope.client.util;

import name.webdizz.gadget.four.envelope.client.domain.Currency;
import name.webdizz.gadget.four.envelope.client.domain.Expense;

import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;

/**
 * @author Izzet_Mustafayev
 * 
 */
public class XmlEnvelopeParser {

	/**
	 * Create {@link Expense} from given XML {@link Node}. The {@link Node} must
	 * contains as a children elements <code>expression</code> and
	 * <code>sum</code> nodes.
	 * 
	 * @param node
	 *            the node to create {@link Expense} from
	 * @return created {@link Expense}
	 */
	public static Expense createExpense(final Node node) {
		Expense expense = new Expense();
		expense.setDate(node.getAttributes().getNamedItem("date")
				.getNodeValue());
		expense.setDefaultAccount(node.getAttributes().getNamedItem(
				"defaultAccount").getNodeValue());
		NodeList childNodes = node.getChildNodes();
		int childLen = childNodes.getLength();
		for (int c = 0; c < childLen; c++) {
			Node childNode = childNodes.item(c);
			if ("expression".equals(childNode.getNodeName())
					&& null != childNode.getFirstChild()) {
				expense.setExpense(childNode.getFirstChild().getNodeValue());
			}
			if ("sum".equals(childNode.getNodeName())
					&& null != childNode.getFirstChild()) {
				expense.setAmount(Float.valueOf(childNode.getFirstChild()
						.getNodeValue()));
			}
		}
		return expense;
	}

	public static Currency createCurrency(final NodeList nodes) {
		Currency currency = null;
		int currencyNodeIndex = 0;
		while (null != nodes.item(currencyNodeIndex)) {
			if ("currency".equals(nodes.item(currencyNodeIndex).getNodeName())) {
				Node currencyNode = nodes.item(currencyNodeIndex);
				String currencyCode = currencyNode.getAttributes()
						.getNamedItem("code").getNodeValue();
				String currencyId = currencyNode.getAttributes().getNamedItem(
						"id").getNodeValue();
				String currencyName = currencyNode.getFirstChild()
						.getNodeValue();
				currency = new Currency(currencyId, currencyName, currencyCode);
				break;
			}
			currencyNodeIndex++;
		}
		return currency;
	}
}
